package com.example.zhu95.mytimber.nowplaying;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.zhu95.mytimber.ConstantValue;
import com.example.zhu95.mytimber.MyApplication;
import com.example.zhu95.mytimber.R;
import com.example.zhu95.mytimber.activity.BaseActivity;
import com.example.zhu95.mytimber.adapters.ItemVpopupAdapter;
import com.example.zhu95.mytimber.entity.PlayQueueRecord;
import com.example.zhu95.mytimber.entity.SongBean;
import com.example.zhu95.mytimber.entity.SongData;
import com.example.zhu95.mytimber.listener.CircleSeekBarChangeListener;
import com.example.zhu95.mytimber.listener.OnMusicGestureListener;
import com.example.zhu95.mytimber.listener.OnPlayNextSongClickListener;
import com.example.zhu95.mytimber.listener.OnPlayPreviousSongClickListener;
import com.example.zhu95.mytimber.listener.PlayPauseBtnOnClickListener;
import com.example.zhu95.mytimber.listener.PlayPauseBtnOnTouchListener;
import com.example.zhu95.mytimber.ui.CircularSeekBar;
import com.example.zhu95.mytimber.utils.Util;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import jp.co.recruit_lifestyle.android.widget.PlayPauseButton;

/**
 * @author zhu95
 * @date 2018/3/22.
 */

public class Timber2 extends BaseTimber {

    @BindView(R.id.img_timber2_header)
    ImageView imgTimber2Header;
    @BindView(R.id.tv_songName)
    TextView tvSongName;
    @BindView(R.id.tv_artist)
    TextView tvArtist;
    @BindView(R.id.header_timber2)
    View headerTimber2;
    @BindView(R.id.circularSeekBar)
    CircularSeekBar circularSeekBar;
    @BindView(R.id.cirimg_album_art)
    CircleImageView cirimgAlbumArt;
    @BindView(R.id.tv_current_time)
    TextView tvCurrentTime;
    @BindView(R.id.recycler_view_playqueue_timber2)
    RecyclerView recyclerViewPlayqueueTimber2;
    @BindView(R.id.btn_play_pause_timber2)
    PlayPauseButton btnPlayPauseTimber2;
    @BindView(R.id.img_previous_timber2)
    ImageView imgPreviousTimber2;
    @BindView(R.id.img_next_timber2)
    ImageView imgNextTimber2;
    @BindView(R.id.img_shuffle)
    ImageView imgShuffle;
    @BindView(R.id.img_repeat)
    ImageView imgRepeat;
    Unbinder unbinder;
    List<SongBean> songs;
    ItemVpopupAdapter adapter;
    byte[] blurImgByte;
    int randomForeColor = Util.INSTANCE.getRandomForeColor();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_timber2, container, false);
        unbinder = ButterKnife.bind(this, view);

        cirimgAlbumArt.setColorFilter(getResources().getColor(randomForeColor));
        imgTimber2Header.setColorFilter(getResources().getColor(randomForeColor));

        if (songs == null) {
            songs = new ArrayList<>();
        }
        adapter = new ItemVpopupAdapter(songs, rootActivity);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(rootActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerViewPlayqueueTimber2.setLayoutManager(linearLayoutManager);
        recyclerViewPlayqueueTimber2.setAdapter(adapter);
        btnPlayPauseTimber2.setColor(Color.WHITE);

        PlayPauseBtnOnClickListener clickListener = new PlayPauseBtnOnClickListener();
        PlayPauseBtnOnTouchListener touchListener = new PlayPauseBtnOnTouchListener(clickListener);
        btnPlayPauseTimber2.setOnTouchListener(touchListener);
        circularSeekBar.setOnSeekBarChangeListener(new CircleSeekBarChangeListener(new CircleSeekBarChangeListener.CallBack() {
            @Override
            public void updateOtherUI(int position) {
                tvCurrentTime.setText(Util.INSTANCE.getPlayTime(position));
            }
        }));
        imgPreviousTimber2.setOnClickListener(new OnPlayPreviousSongClickListener());
        imgNextTimber2.setOnClickListener(new OnPlayNextSongClickListener());
        OnMusicGestureListener onMusicGestureListener = new OnMusicGestureListener();
        onMusicGestureListener.enableDoubleClick(true);
        onMusicGestureListener.enableFling(true);
        final GestureDetector gestureDetector = new GestureDetector(rootActivity, onMusicGestureListener);
        headerTimber2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                gestureDetector.onTouchEvent(event);
                return true;
            }
        });
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        songs = PlayQueueRecord.Companion.getPlayqueueSongs();
        adapter.setSongs(songs);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void updateUI(int songid, String musicState, int currentPosition) {
        adapter.notifyDataSetChanged();
        updateHeaderUI(songid, musicState, currentPosition);
    }

    private void updateHeaderUI(int songid, String musicState, int currentPosition) {
        SongBean song = SongData.findSongByID(songid);
        if (song == null) {
            return;
        }

        tvSongName.setText(song.getTitle());
        tvArtist.setText(song.getArtist());
        circularSeekBar.setMax(song.getDuration());
        circularSeekBar.setProgress(currentPosition);
        tvCurrentTime.setText(Util.INSTANCE.getPlayTime(currentPosition));
        String albumArt = song.getAlbumArt();
        updatePlayModeView();

        byte[] bytes;
        if (!TextUtils.isEmpty(albumArt)) {
            bytes = Util.INSTANCE.getBlurBytes(albumArt);
            Glide.with(this).load(albumArt).centerCrop().into(cirimgAlbumArt);
        } else {
            bytes = Util.INSTANCE.getBlurBytes(R.drawable.ic_empty_music2);
            Glide.with(this).load(R.drawable.ic_empty_music2).centerCrop().into(cirimgAlbumArt);
        }
        if (bytes != blurImgByte) {
            blurImgByte = bytes;
            Glide.with(MyApplication.getContext()).load(bytes).centerCrop().into(imgTimber2Header);
        }
        BaseActivity.updatePlayPauseBtnState(btnPlayPauseTimber2, musicState);
    }

    private void updatePlayModeView() {
        int playMode = PlayQueueRecord.Companion.getPlayModeFromDB();
        int colorAccent = getResources().getColor(R.color.colorAccent);
        if (playMode == ConstantValue.PLAYMODE_RANDOM) {
            imgShuffle.setColorFilter(colorAccent);
            imgRepeat.setColorFilter(Color.WHITE);
        } else if (playMode == ConstantValue.PLAYMODE_SINGLE) {
            imgRepeat.setColorFilter(colorAccent);
            imgShuffle.setColorFilter(Color.WHITE);
        } else {
            imgRepeat.setColorFilter(Color.WHITE);
            imgShuffle.setColorFilter(Color.WHITE);
        }
    }

    @Override
    public void updateProgress(int songid, final int currentPosition) {
        final SongBean song = SongData.findSongByID(songid);
        if (song != null) {
            rootActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    circularSeekBar.setMax(song.getDuration());
                    circularSeekBar.setProgress(currentPosition);
                    tvCurrentTime.setText(Util.INSTANCE.getPlayTime(currentPosition));
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.img_shuffle, R.id.img_repeat})
    public void onViewClicked(View view) {
        int playmode = PlayQueueRecord.Companion.getPlayModeFromDB();
        switch (view.getId()) {
            case R.id.img_shuffle: {
                if (playmode == ConstantValue.PLAYMODE_RANDOM) {
                    playmode = ConstantValue.PLAYMODE_SEQUENCE;
                } else {
                    playmode = ConstantValue.PLAYMODE_RANDOM;
                }
            }
            break;
            case R.id.img_repeat: {
                if (playmode == ConstantValue.PLAYMODE_SINGLE) {
                    playmode = ConstantValue.PLAYMODE_SEQUENCE;
                } else {
                    playmode = ConstantValue.PLAYMODE_SINGLE;
                }
            }
            break;
            default:
        }
        PlayQueueRecord playQueueRecord = new PlayQueueRecord();
        playQueueRecord.setPlayMode(playmode);
        if (playmode == ConstantValue.PLAYMODE_SEQUENCE) {
            playQueueRecord.setToDefault("playMode");
        }
        playQueueRecord.updateAll();
        updatePlayModeView();
    }
}
